#!/usr/bin/python

"""Model definitions for django-cachewizard."""

__author__ = 'Sumeet Singh (sumeets@singhsays.com)'


# Imports
from django.db import models
from django.utils import simplejson


class FormsCache(models.Model):
  """Model representing the cache associated with a form wizard."""
  instance = models.CharField(max_length=255)
  data = models.TextField()

  def get_data(self):
    """Method to deserialize and return self.data."""
    if self.data:
      data_dict = simplejson.loads(self.data)
    else:
      data_dict = {}
    return data_dict

  def set_form(self, form, data):
    """Method to add/update form data to cache."""
    data_dict = self.get_data()
    data_dict[str(form)] = data
    self.data = simplejson.dumps(data_dict)
    self.save()

  def get_form(self, form):
    """Method to fetch form data from cache."""
    form = str(form)
    data_dict = self.get_data()
    if form in data_dict:
      return data_dict[form]

  @classmethod
  def get_cache(cls, instance=None):
    """Static method to fetch or create FormsCache for a given instance."""
    if instance is not None:
      try:
        cache = FormsCache.objects.get(instance=instance)
      except FormsCache.DoesNotExist:
        cache = FormsCache(instance=instance)
        cache.save()
      return cache
